package com.cn.xiaonuo.tcrfinance.tcrgnete.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.ExportExcelUtils;
import com.cn.xiaonuo.common.vo.ExcelData;
import com.cn.xiaonuo.core.exception.ServiceException;
import com.cn.xiaonuo.tcrfinance.tcrgnete.entiey.PvShopWallet;
import com.cn.xiaonuo.tcrfinance.tcrgnete.entiey.ShopSettlement;
import com.cn.xiaonuo.tcrfinance.tcrgnete.mapper.PvShopWalletMapper;
import com.cn.xiaonuo.tcrfinance.tcrgnete.mapper.ShopSettlementMapper;
import com.cn.xiaonuo.tcrfinance.tcrgnete.param.SettlementPageParam;
import com.cn.xiaonuo.tcrfinance.tcrgnete.param.ShopIncomingPartsParam;
import com.cn.xiaonuo.tcrfinance.tcrgnete.service.ShopSettlementService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: slb-reports-java
 * @Author: likui
 * @CreateTime: 2022-11-10  09:15
 * @Description: TODO
 */
@Slf4j
@Service
public class ShopSettlementServiceImpl implements ShopSettlementService {

    @Autowired
    private ShopSettlementMapper shopSettlementMapper;

    @Autowired
    private PvShopWalletMapper pvShopWalletMapper;

    @Override
    public BusinessMessage pageShopSettlement(SettlementPageParam param) {
        BusinessMessage message = new BusinessMessage();
        HashMap<String, Object> map = new HashMap<>();
        if (param.getType().equals(2)&&ObjectUtils.isEmpty(param.getPsNo())){
            message.setMessage("该商家暂未进件!");
            message.setCode(Status.failCode);
            message.setSuccess(false);
            return message;
        }
        QueryWrapper queryWrapper = this.queryWrapper(param);
        PageHelper.startPage(param.getCurrentPage(),param.getPageSize());
        List<ShopSettlement> shopSettlements = shopSettlementMapper.selectList(queryWrapper);
        PageInfo<ShopSettlement> pageInfo = new PageInfo<>(shopSettlements);
        map.put("pageInfo",pageInfo);
        Map<String,Object> totalSubLedger=shopSettlementMapper.totalSubLedger(param);
        map.put("settlementAmount",totalSubLedger.get("settlementAmount"));
        map.put("merFee",totalSubLedger.get("merFee"));
        map.put("platformFee",totalSubLedger.get("platformFee"));
        message.setData(map);
        message.setMessage(Status.success);
        message.setCode(Status.successCode);
        message.setSuccess(true);
        return message;
    }

    @Override
    public void shopSettlementExcel(HttpServletResponse response, SettlementPageParam param) {
        SimpleDateFormat ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper queryWrapper = this.queryWrapper(param);
        List<ShopSettlement> shopSettlements = shopSettlementMapper.selectList(queryWrapper);
        try {
            List<List<Object>> rows = new ArrayList();
            ExcelData data = new ExcelData();
            data.setName("现金分账处理记录导出");//sheet表名称
            //表头
            List<String> titles = new ArrayList();
            titles.add("商户订单号");
            titles.add("分账单号");
            titles.add("订单实付金额(元)");
            titles.add("运营商分账金额(元)");
            titles.add("平台分账金额(元)");
            titles.add("广联手续费(元)");
            titles.add("分账接收方编码");
            titles.add("所属运营商");
            titles.add("订单类型");
            titles.add("处理状态");
            titles.add("支付日期");
            titles.add("发起时间");
            titles.add("分账完成时间");
            titles.add("分账结果备注");
            titles.add("订单编号");
            data.setTitles(titles);
            for (ShopSettlement settlement:shopSettlements){
                List<Object> row1 = new ArrayList();
                row1.add(settlement.getMerchantOrderNo());
                row1.add(settlement.getSettlementNo());
                row1.add(settlement.getTotalAmount().doubleValue()/100);
                row1.add(settlement.getSettlementAmount().doubleValue()/100);
                if (ObjectUtils.isEmpty(settlement.getPlatformFee())){
                    row1.add("0");
                }else {
                    row1.add(settlement.getPlatformFee().doubleValue()/100);
                }
                if (ObjectUtils.isEmpty(settlement.getMerFee())){
                    row1.add("0");
                }else {
                    row1.add(settlement.getMerFee().doubleValue()/100);
                }
                row1.add(settlement.getPsNo());
                row1.add(settlement.getShopName());
                if (ObjectUtils.isEmpty(settlement.getOrderStatus())){
                    row1.add("其他");
                }else {
                    if (settlement.getOrderStatus().equals(1)){
                        row1.add("活动订单");
                    }else if (settlement.getOrderStatus().equals(2)){
                        row1.add("普通订单");
                    }
                }
                if (settlement.getSettlementStatus().equals(0)){
                    row1.add("分账暂停");
                }else if (settlement.getSettlementStatus().equals(1)){
                    row1.add("分账待提交");
                }else if (settlement.getSettlementStatus().equals(2)){
                    row1.add("分账待处理");
                }else if (settlement.getSettlementStatus().equals(3)){
                    row1.add("分账处理成功");
                }else if (settlement.getSettlementStatus().equals(4)){
                    row1.add("分账处理失败");
                }else {
                    row1.add("");
                }
                String payTime = ymdhms.format(settlement.getPayTime());
                row1.add(payTime);
                if (ObjectUtils.isNotEmpty(settlement.getOrderTime())){
                    String orderTime = ymdhms.format(settlement.getOrderTime());
                    row1.add(orderTime);
                }else {
                    row1.add("");
                }
                if (ObjectUtils.isNotEmpty(settlement.getSettlementTime())){
                    String settlementTime = ymdhms.format(settlement.getSettlementTime());
                    row1.add(settlementTime);
                }else {
                    row1.add("");
                }
                row1.add(settlement.getRemark());
                row1.add(settlement.getSerialNumber());
                rows.add(row1);
            }
            data.setRows(rows);
            ExportExcelUtils.exportExcel(response, "现金分账处理记录.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public BusinessMessage shopIncomingParts(HttpServletRequest request) throws IOException {
        BusinessMessage message = new BusinessMessage();
        byte[] reqByte = IOUtils.toByteArray(request.getInputStream());
        if (reqByte == null) {
            log.error("好收银进件回调失败,响应信息为空...");
            message.setMessage("好收银进件回调失败");
            message.setCode("-1");
            message.setSuccess(false);
            return message;
        }
        ShopIncomingPartsParam shopIncomingPartsParam = JSON.parseObject(new String(reqByte, "UTF-8"), ShopIncomingPartsParam.class);
        if (ObjectUtil.isEmpty(shopIncomingPartsParam) && shopIncomingPartsParam.isNull()){
            message.setCode("-1");
            message.setSuccess(false);
            return message;
        }
        log.info("获取到的进件信息是：{}",shopIncomingPartsParam.toString());
        if (shopIncomingPartsParam.getAuditStatus().equals(6)){
            LambdaQueryWrapper<PvShopWallet> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PvShopWallet::getStatus, 1);
            wrapper.eq(PvShopWallet::getDeleted, 0);
            wrapper.eq(PvShopWallet::getUserId, shopIncomingPartsParam.getOwnerId());
            wrapper.eq(PvShopWallet::getChannelType,50);
            PvShopWallet pvShopWallet = pvShopWalletMapper.selectOne(wrapper);
            log.info("商户信息为{}",pvShopWallet);
            if (ObjectUtils.isEmpty(pvShopWallet)){
                message.setCode(Status.failCode);
                message.setMessage("商户账号不存在!");
                message.setSuccess(false);
                throw new ServiceException(-1,"商户账号不存在!");
            }else {
                pvShopWallet.setPsNo(shopIncomingPartsParam.getPsNo());
                pvShopWalletMapper.updateById(pvShopWallet);
                message.setCode(Status.successCode);
                message.setMessage(Status.success);
                message.setSuccess(true);
            }
        }
        return message;
    }

    @Override
    public void subLedgerEntryRecordExcel(HttpServletResponse response, SettlementPageParam param) {
        SimpleDateFormat ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper queryWrapper = this.queryWrapper(param);
        List<ShopSettlement> shopSettlements = shopSettlementMapper.selectList(queryWrapper);
        try {
            List<List<Object>> rows = new ArrayList();
            ExcelData data = new ExcelData();
            data.setName("现金分账处理记录导出");//sheet表名称
            //表头
            List<String> titles = new ArrayList();
            titles.add("商户订单号");
            titles.add("分账单号");
            titles.add("支付时间");
            titles.add("提交时间");
            titles.add("分账完成时间");
            titles.add("分账入账金额(元)");
            titles.add("订单类型");
            data.setTitles(titles);
            for (ShopSettlement settlement:shopSettlements){
                List<Object> row1 = new ArrayList();
                row1.add(settlement.getMerchantOrderNo());
                row1.add(settlement.getSettlementNo());
                String payTime = ymdhms.format(settlement.getPayTime());
                row1.add(payTime);
                if (ObjectUtils.isNotEmpty(settlement.getOrderTime())){
                    String orderTime = ymdhms.format(settlement.getOrderTime());
                    row1.add(orderTime);
                }else {
                    row1.add("");
                }
                if (ObjectUtils.isNotEmpty(settlement.getSettlementTime())){
                    String settlementTime = ymdhms.format(settlement.getSettlementTime());
                    row1.add(settlementTime);
                }else {
                    row1.add("");
                }
                row1.add(settlement.getSettlementAmount().doubleValue()/100);
                if (ObjectUtils.isEmpty(settlement.getOrderStatus())){
                    row1.add("其他");
                }else {
                    if (settlement.getOrderStatus().equals(1)){
                        row1.add("活动订单");
                    }else if (settlement.getOrderStatus().equals(2)){
                        row1.add("普通订单");
                    }
                }
                rows.add(row1);
            }
            data.setRows(rows);
            ExportExcelUtils.exportExcel(response, "现金分账处理记录.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public QueryWrapper queryWrapper(SettlementPageParam param){
        QueryWrapper<ShopSettlement> wrapper = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(param.getPayBeginTime()) && ObjectUtils.isNotEmpty(param.getPayEndTime())){
            wrapper.between("pay_time",param.getPayBeginTime(),param.getPayEndTime());
        }
        if (ObjectUtils.isNotEmpty(param.getOrderBeginTime()) && ObjectUtils.isNotEmpty(param.getOrderEndTime())){
            wrapper.between("order_time",param.getOrderBeginTime(),param.getOrderEndTime());
        }
        if (ObjectUtils.isNotEmpty(param.getMerchantOrderNo())){
            wrapper.eq("merchant_order_no",param.getMerchantOrderNo());
        }
        if (ObjectUtils.isNotEmpty(param.getSettlementNo())){
            wrapper.eq("settlement_no",param.getSettlementNo());
        }
        if (ObjectUtils.isNotEmpty(param.getOrderType())){
            wrapper.eq("order_type",param.getOrderType());
        }
        if (ObjectUtils.isNotEmpty(param.getOrderStatus())){
            wrapper.eq("order_status",param.getOrderStatus());
        }
        if (ObjectUtils.isNotEmpty(param.getSettlementStatus())){
            wrapper.eq("settlement_status",param.getSettlementStatus());
        }
        if (ObjectUtils.isNotEmpty(param.getSettlementBeginTime()) && ObjectUtils.isNotEmpty(param.getSettlementEndTime())){
            wrapper.between("settlement_time",param.getSettlementBeginTime(),param.getSettlementEndTime());
        }
        if (ObjectUtils.isNotEmpty(param.getSerialNumber())){
            wrapper.eq("serial_number",param.getSerialNumber());
        }
        if (ObjectUtils.isNotEmpty(param.getSettleStatus())){
            wrapper.eq("settle_status",param.getSettleStatus());
        }
        if (ObjectUtils.isNotEmpty(param.getPsNo())){
            wrapper.eq("ps_no",param.getPsNo());
        }
        if (ObjectUtils.isNotEmpty(param.getShopId())){
            wrapper.eq("shop_id",param.getShopId());
        }
        wrapper.orderByDesc("created_time");
        return wrapper;
    }


}
